#include "agingDeamon.h"

void run(){
	while(!agingDeamonExit){
		int i ;
		for (i = 0; i < ShiftClock; i++) {
			 sem_wait(&deamonSem);
		}
		writerStart();
		updateAges();
		writerEnd();
		for (i = 0; i < ShiftClock; i++) {
			 sem_post(&clockSem);
		}
		if (agingDeamonExit == 1) break;
	}
}



void initAgingDeamon(){
	agingDeamonExit = 0;
	pthread_create(&agingDeamon, NULL, (void*)&run, NULL);
}

void updateAges(){
	int i ;
	for (i = 0; i < NumOfPagesInMM; i++){
		unsigned int age = ipt[i].ageReg;
		 age = age >> 1;
		if (ipt[i].referenceBit == 1)
		{
			age += 0x80000000;
		}
		ipt[i].ageReg = age;
		ipt[i].referenceBit = 0;
	}
}

void killAgingDeamon()
{
	agingDeamonExit = 1;
	int i;
	for (i = 0; i < ShiftClock; i++){
		sem_post(&deamonSem);
	}
	pthread_join(agingDeamon,NULL);
	//FREE(agingDeamon);

}
